<template>
  <view class="addressContainer pt10">
    <AtForm>
      <AtInput
        name='merchantName' 
        title='商户名称' 
        type='text' 
        placeholder='请输入商户/公司名称' 
        :value="state.merchantName"
        :onChange="(val)=>{handleChange(val,'merchantName')}"
      />
      <view class="myrow">
        <view class="at-row ">
          <view class="adname">公司地址</view>
          <view class="cbbb at-col at-col-7 ellipsis-1">{{state.merchantAddress}}</view>
          <view class="at-col at-col-2"><AtTag type='primary' size="small" :onClick="getAdress">获取地址</AtTag></view>
        </view>
      </view>      
      <AtInput
        name='contactName' 
        title='联系姓名' 
        type='text' 
        placeholder='请输入联系人姓名' 
        :value="state.contactName"
        :onChange="(val)=>{handleChange(val,'contactName')}"
      />
      <AtInput
        name='contactPhone' 
        title='联系电话' 
        type='phone'
        placeholder='请输入联系电话' 
        :value="state.contactPhone"
        :onChange="(val)=>{handleChange(val,'contactPhone')}"
      />
      <view class="myrow">
        <view class="at-row ">
          <view class="adname">服务区域</view>
          <view class="at-col at-col cbbb">
              <picker mode="region" :value="state.serviceArea" customItem="全部" @change="onAreaChange">
                {{areaName}}
             </picker>
          </view>
        </view>
      </view> 

      <view class="bgfff pb10">
        <AtListItem
            class="bgfff"
            title='门店照片'
        />
        <AtImagePicker
            class="pl20"
            mode='scaleToFill'
            :multiple="false"
            :count="1"
            :showAddBtn="showAddBtn"
            :files="state.picture"
            :onChange="onChangePic"
            :onFail="onFail"
            :onImageClick="onImageClick"
        />
      </view>

     <view class="bgfff">
        <AtListItem
            class="bgfff"
            title='营业执照'
        />
        <AtImagePicker
            class="pl20 pb20"
            mode='scaleToFill'
            :multiple="false"
            :count="1"
            :showAddBtn="showAddBtn2"
            :files="state.license"
            :onChange="onChangeLicense"
            :onFail="onFail"
            :onImageClick="onImageClick2"
        />
      </view>
      
      
      <view class="pl20 pr20">
          <AtTextarea
            v-model:value="state.serviceDesc"
            :height="200"
            :maxLength="300"
            placeholder='请填写服务内容简介'
            />
      </view>
      <view class="mt30 pl20 pr20">
          <AtButton formType='submit' type="primary" :onClick="onSubmit">立即入驻接单</AtButton>
      </view>
    </AtForm>
  </view>
</template>

<script setup>
import Taro, { showToast } from "@tarojs/taro"
import { getCurrentInstance, onMounted, reactive, computed, ref } from "vue";

import request from "../../utils/request"

const {ctx} = getCurrentInstance();

const showAddBtn = ref(true)
const showAddBtn2 = ref(true)

const state = reactive({
    merchantName: '',
    picture: [],
    merchantAddress: '',
    contactName: '',
    contactPhone: '',
    license: [],
    serviceArea: '',
    serviceDesc: '',
})

const areaName = computed(()=>{
    let name = '';
    if (state.serviceArea && state.serviceArea.length > 0) {
        if (state.serviceArea[2] !== '全部') {
            name = state.serviceArea.join('')
        }else if(state.serviceArea[1] !== '全部'){
            name = state.serviceArea[0]+state.serviceArea[1]
        }else if(state.serviceArea[0] !== '全部'){
            name = state.serviceArea[0]
        }else{
            name = '全国地区'
        }
    }else{
        name = '请选择服务区域'
    }
    return name;
})

const onAreaChange = (e)=>{
    console.log(e);
    state.serviceArea = e.target.value
}


const getAdress = ()=>{
  Taro.chooseLocation().then((res)=>{
    console.log(res);
    state.merchantAddress = res.address
  })
}

const handleChange = (val,field)=>{
  state[field] = val
}

const onChangePic = async (res)=>{
  console.log(res);
  let type = res.operationType
  let index = res.index
  if (type == 'add') {
      res.files.forEach(item=>{
        if (item.imageId) {
          return
        }
        Taro.uploadFile({
          url:`${BASEAPI}/upload`,
          filePath: item.url,
          name:'file',
          header: {
            'content-type': 'multipart/form-data'
          },
          complete:res=>{
            console.log(typeof res.data);
            console.log(res);
            if (res.data) {
              let data = JSON.parse(res.data)
              state.picture.push({url:"http://"+data.data[0].imageUrl, imageId:data.data[0].imageId})
              showToast({
                title:'上传成功'
              })
              showAddBtn.value = false
            }
            
          }
        })
      })
  } else if(type == "remove"){
    showToast({
      title:'删除成功'
    })
    state.picture.splice(index,1)
    showAddBtn.value = true
  }
}

const onChangeLicense = async (res)=>{
  console.log(res);
  let type = res.operationType
  let index = res.index
  if (type == 'add') {
      res.files.forEach(item=>{
        if (item.imageId) {
          return
        }
        Taro.uploadFile({
          url:`${BASEAPI}/upload`,
          filePath: item.url,
          name:'file',
          header: {
            'content-type': 'multipart/form-data'
          },
          complete:res=>{
            if (res.data) {
              let data = JSON.parse(res.data)
              state.license.push({url:"http://"+data.data[0].imageUrl, imageId:data.data[0].imageId})
              showToast({
                title:'上传成功'
              })
              showAddBtn2.value = false
            }
            
          }
        })
      })
  } else if(type == "remove"){
    showToast({
      title:'删除成功'
    })
    state.license.splice(index,1)
    showAddBtn2.value = true
  }
}

const onFail = (error)=>{
  console.log(error);
  console.log(error.errMsg == 'chooseImage:fail cancel');
}

const onImageClick = (index, file)=>{
  let urls = state.picture.map(el=>el.url)
  Taro.previewImage({
    current: file.url, // 当前显示图片的http链接
    urls: urls // 需要预览的图片http链接列表
  })
}

const onImageClick2 = (index, file)=>{
  let urls = state.license.map(el=>el.url)
  Taro.previewImage({
    current: file.url, // 当前显示图片的http链接
    urls: urls // 需要预览的图片http链接列表
  })
}



const onSubmit = async ()=>{
    let res = await request('/merchantEnter/create','post',state)
    console.log(res);
    showToast({
      title:res.msg
    })
    setTimeout(() => {
      Taro.navigateBack()
    }, 1500);
}

onMounted(async()=>{
 
})
</script>

<style lang="scss">
.addressContainer{
  .at-form::after{
    border-top-width: 0px;
    border-bottom-width: 0px;
  }
  .myrow{
    height: 96px;
    line-height: 96px;
    border-bottom: 1px solid #d6e4ef;
    font-size: 32px;
    margin-left: 30px;
    .adname{
      width: 144px;
      margin-right: 16px;
    }
  }
  .at-input__title {
    width: 144px;
  }

  .serviceArea{
      display: flex;
      justify-content: space-between;
  }
}

</style>